//
//  BTEWebViewViewController.swift
//  BTE
//
//  Created by Mike Zhang on 2025/8/5.
//


import UIKit
import StoreKit
@preconcurrency import WebKit

class BTEWebViewViewController: BTEBaseViewController, WKNavigationDelegate, WKUIDelegate, WKScriptMessageHandler {

    private let progressView: UIProgressView = {
        let progress = UIProgressView(progressViewStyle: .default)
        progress.tintColor = .blue
        progress.isHidden = true
        return progress
    }()
    
    private var webView: WKWebView!
    private var urlString: String?

    // MARK: - Initializer
    init(url: String? = nil) {
        self.urlString = url
        super.init(nibName: nil, bundle: nil)
        setupUI()
        loadWebContent()
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    // MARK: - View Lifecycle
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white
    }

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        bringViewsToFront()
    }

    deinit {
        webView.removeObserver(self, forKeyPath: "estimatedProgress")
    }

    // MARK: - UI Setup
    private func setupUI() {
        setupWebView()
        setupProgressView()
    }

    private func setupWebView() {
        let userContentController = WKUserContentController()
        let config = WKWebViewConfiguration()
        config.userContentController = userContentController
        ["Yiddishism", "possibilities", "gnarliest", "prankt", "theotechnic"].forEach { name in
            userContentController.add(self, name: name)
        }

        webView = WKWebView(frame: .zero, configuration: config)
        webView.navigationDelegate = self
        webView.uiDelegate = self
        webView.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(webView)
        setupWebViewConstraints()
        webView.addObserver(self, forKeyPath: "estimatedProgress", options: .new, context: nil)
    }

    private func setupProgressView() {
        view.addSubview(progressView)
        progressView.snp.makeConstraints {
            $0.left.right.equalToSuperview();
            $0.top.equalTo(navigationBar.snp.bottom);
            $0.height.equalTo(5)
        }
    }

    private func setupWebViewConstraints() {
        webView.snp.makeConstraints {
            $0.left.right.bottom.equalToSuperview()
            $0.top.equalTo(navigationBar.snp.bottom)
        }
    }

    private func loadWebContent() {
        guard let urlString = urlString, let url = URL(string: urlString) else { return }
        webView.load(URLRequest(url: url))
    }

    // MARK: - Observers
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        guard keyPath == "estimatedProgress" else { return }
        progressView.progress = Float(webView.estimatedProgress)
        progressView.isHidden = webView.estimatedProgress >= 1.0
    }

    // MARK: - WKScriptMessageHandler
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        switch message.name {
        case "Yiddishism": handleBackNavigation()
        case "possibilities": handleRootNavigation()
        case "gnarliest": requestAppReview()
        case "prankt": handleGooseyMessage(message.body)
        case "theotechnic": handleSurpriseMessage()
        default: break
        }
    }

    private func handleBackNavigation() {
        navigationController?.popViewController(animated: true)
    }

    private func handleRootNavigation() {
        navigationController?.popToRootViewController(animated: false)
        if  let windowScene = UIApplication.shared.connectedScenes
            .first(where: { $0.activationState == .foregroundActive }) as? UIWindowScene,
              let rootVC = windowScene.windows.first(where: { $0.isKeyWindow })?.rootViewController  as? UITabBarController {
            rootVC.selectedIndex = 0
            (rootVC as! BTEBaseTabBarController).basetabbar.la.image = UIImage.init(named: "gwerger432323232")
            (rootVC as! BTEBaseTabBarController).basetabbar.ed.image = UIImage.init(named: "fwef32323232er23")
        }
    }

    private func requestAppReview() {
        if let scene = UIApplication.shared.connectedScenes.first(where: { $0.activationState == .foregroundActive }) as? UIWindowScene {
            SKStoreReviewController.requestReview(in: scene)
        }
    }

    private func handleGooseyMessage(_ body: Any) {
        if let bodyArray = body as? [String], let firstItem = bodyArray.first {
            navigationController?.popToRootViewController(animated: false)
            BTEUrlToolsManager.shared.handleURL(firstItem, in: self, model: nil)
        }
    }

    private func handleSurpriseMessage() {
        let t = TrackingEvent.init(step: "9", startTimestamp: "\(Date().timeIntervalSince1970)", endTimestamp: "\(Date().timeIntervalSince1970)")
        BTELocationReporterManager.shared.reportLocation(for: t)
    }

    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        DispatchQueue.main.asyncAfter(deadline: .now() + 1) {[weak self] in
            self?.updateNavigationTitle(webView.title ?? "")
        }
    }

    private func bringViewsToFront() {
        view.bringSubviewToFront(webView)
        view.bringSubviewToFront(progressView)
    }
}
